import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js';
import 'monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution';
import "regenerator-runtime/runtime.js";
import './style.css';
const input = document.querySelector('input[type=file]');
const saveBtn = document.querySelector('.save-btn');
let monacoInstance = null;

/** 编辑器构造函数 */
class MonacoEditor {
    constructor(dom, options) {
        this.instance = monaco.editor.create(dom, options);
        console.log(this.instance.getValue());
    }
    setValue(value) {
        this.instance.setValue(value);
    }
    getValue(value) {
        return this.instance.getValue();
    }
}

/** input事件 */
input.addEventListener('change', () => {
    const reader = new FileReader()
    reader.readAsText(input.files[0], 'utf8') // input.files[0]为第一个文件
    reader.onload = () => {
        if(monacoInstance == null) {
            monacoInstance = new MonacoEditor(document.getElementById("monaco"), {
                value: reader.result,
                curTheme: 'vs-dark',

            }); 
            monacoInstance.instance.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function () {
                alert('保存成功');
            })            
            return;
        }
        monacoInstance.setValue(reader.result);
    }
}, false);

saveBtn.addEventListener('click', async () => {
    if(!monacoInstance) {
        return alert('请选择文件'); 
    }
    if(monacoInstance.getValue().length == 0) {
        return alert('内容不得为空');
    }
    const opts = {
        types: [{
            description: 'file',
            accept: {
                'file/*': ['.js']
            },
        }],
    };
    let fileHandle;
    // 创建文件写入的writableStream
    fileHandle = await window.showSaveFilePicker(opts);
    const writable = await fileHandle.createWritable();
    // 将edtior内容转换为blob对象 
    const fileBolb = new Blob([monacoInstance.getValue()], {
        type: "text/plain;charset=utf-8"
    })
    // 写入文件
    await writable.write(fileBolb);
    await writable.close();
});